package com.cxq.safe.synchronizedlock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by cxq on 2020/7/25.
 */
public class Tickets  implements Runnable{
    private int ticket = 100;
    //定义锁对象：构造函数参数为线程是否公平获取锁true-公平；false-不公平，即由某个线程独占，默认是false
    private ReentrantLock lock = new ReentrantLock(true);

    @Override
    public void run() {
        while(true){
            lock.lock();
            //lock方法后面必须跟try{}finally{}语句
            try {
                if (ticket > 0) {
                    try {
                        //模拟出票时间
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //打印进程号和票号，票数减1
                    String name = Thread.currentThread().getName();
                    System.out.println("线程" + name + "售票" + ticket--);
                }
            }finally {
                lock.unlock();
            }
        }
    }
}
